<?php
class ProjectsController extends AppController {

	var $name = 'Projects';
	var $uses = array('Project', 'User');
	
	function beforeFilter() {
		parent::beforeFilter();
		
		if ($this->Auth->user('role') != 'admin')
		{
			$this->redirect('/');
		}
	}
	
	function control_projects()
	{
		
		$this->Project->recursive = 0;
		$this->set('projects', $this->Project->find('all'));
		
	}

	function add() {
		
		if (!empty($this->data)) {
			$this->Project->create();
			$this->data['Project']['creator_id'] = $this->Auth->user('id');
			if ($this->Project->save($this->data)) {
				$this->Session->setFlash(__('The project has been saved', true));
				$this->redirect(array('action' => 'control_projects'));
			} else {
				$this->Session->setFlash(__('The project could not be saved. Please, try again.', true));
			}
		}
		$users = $this->Project->User->find('list', array('fields' => array('id', 'username')));
		$this->set('users', $users);
	}

	function edit($id = null) {
		
		if (!$id && empty($this->data)) {
			$this->redirect('/');
		}
		
		if (!empty($this->data)) {
			if ($this->Project->save($this->data)) {
				$this->Session->setFlash(__('The project has been saved', true));
				$this->redirect(array('action' => 'control_projects'));
			} else {
				$this->Session->setFlash(__('The project could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data))
		{
			$project = $this->Project->find('first', array('conditions' => array('Project.id' => $id)));
			$this->data = $project;
		}
		else
		{
			$project = $this->Project->find('first', array('conditions' => array('Project.id' => $this->data['Project']['id'])));
		}
		
		$users_in_project = array();
		foreach ($project['User'] as $user)
		{
			$users_in_project[$user['id']] = $user['username'];
		}
		
		$other_users = $this->User->find('list', array(
			'fields' => array('id', 'username'),
			'conditions' => array('User.id NOT IN ('.implode(',', array_keys($users_in_project)).')')
		));
		
		$this->set(compact('users_in_project', 'other_users'));
	}
	
}
